<?php
/**
 * Created by PhpStorm.
 * User: Yui
 * Date: 2017/5/16 0016
 * Time: 15:41
 */

namespace common\models;

use Yii;
use yii\base\Model;

class MemberLogin extends Model
{
    public $mobile;
    public $password;
    private $_Member;

    public function rules()
    {
        return [
            [['mobile', 'password'], 'required'],
            ['mobile', 'match', 'pattern' => '/^1[34578]\d{9}$/', 'message' => '手机号码格式错误'],
            ['password', 'string', 'min' => 6, 'message' => '会员密码至少6个字符'],
            ['password', 'validatePassword', 'message' => '手机号或密码错误'],
        ];
    }

    /**
     * 验证密码
     * @param $attribute
     */
    public function validatePassword($attribute)
    {
        if (!$this->hasErrors()) {
            $this->_Member = $this->getMember();
            if (empty($this->_Member) || !Yii::$app->security->validatePassword($this->password, $this->_Member->password)) {
                $this->addError($attribute, '账号或密码错误');
            }
        }
    }

    /**
     * 获取会员
     */
    public function getMember()
    {
        if ($this->_Member === null) {
            $this->_Member = Member::findByMobile($this->mobile);
        }
        return $this->_Member;
    }

    public function attributeLabels()
    {
        return (new Member())->attributeLabels();
    }
}